<template>
  <div>
    <AuModal
      v-if="isModal"
      v-model="showAddStorePopup"
      :title="t(title)"
      :width="460"
      :padding="false"
      :show-minimize="showMinimize"
      @handleConfirm="storeFormRef.submit()"
      @close="close"
    >
      <div class="pt-[30px] pb-[12px] pl-[10px] pr-[20px] flex justify-center">
        <AuForm
          ref="storeFormRef"
          :key="storeData?.id ?? 'none'"
          :formList="storeFormList"
          :formData="storeFormData"
          :isInline="false"
          :hiddenBtn="true"
          :hasUnfold="false"
          class="!w-[406px]"
          @submit="handleStoreForm"
        />
      </div>

      <template #footer_left>
        <el-button type="primary" link class="mt-[4px]" @click="addGroupForm">
          <FontIcon icon="icon-plus" />&nbsp;{{
            t("device_manage.form.add_store_group")
          }}
        </el-button>
      </template>
    </AuModal>

    <AuForm
      v-else
      ref="storeFormRef"
      :hiddenBtn="true"
      :hasUnfold="false"
      :formList="storeFormList"
    />

    <group-modal
      v-model="showAddGroupModal"
      :show-minimize="showMinimize"
      :action-type="ACTION_TYPE.TADD"
      @submit="handleGroupForm"
    />
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeMount, onMounted, ref, watch } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuModal } from "@/components/AuModal";
import {
  addStoreGroup,
  getGroupList,
  GroupProp,
  uptStoreGroup
} from "@/api/teaInfuser/store";
import { handleTree } from "@/utils/tree";
import { getProvinceCity } from "@/api/user";
import { storeAcList } from "@/views/teaInfuser/device/deviceManage/storeList";
import { cloneDeep } from "lodash-unified";
import GroupModal from "@/views/teaInfuser/store/storeGroup/groupModal.vue";
import { ACTION_TYPE } from "@/components/AuTable/type";
import { ElMessage } from "element-plus";
import { storeGroupSelect } from "@/utils/formSelect";
import { getReleaseSelect } from "@/api/teaInfuser/formula";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "StoreModal"
});

const props = defineProps({
  showModal: {
    type: Boolean,
    default: false
  },
  storeData: {
    type: Object,
    default: () => {
      return {};
    }
  },
  isModal: {
    type: Boolean,
    default: true
  },
  showMinimize: {
    type: Boolean,
    default: true
  }
});
const emit = defineEmits(["handleConfirm", "update:showModal"]);

// region 声明ref变量集合
const showAddStorePopup = ref(false);
const provinceCity = ref([]);
const storeFormList = ref([]);
const storeFormData = ref<Record<string, any>>({});
const title = ref("新增门店");

const showAddGroupModal = ref(false);

const storeFormRef = ref();
// endregion

// region 公共方法的集合
const getGroupSelectList = async () => {
  const select = await storeGroupSelect(
    "group_id",
    {
      label: "device_manage.form.store_group",
      props: {
        checkStrictly: true
      }
    },
    false
  );

  storeFormRef.value.setFormProps("group_id", select);
};

const getList = async () => {
  await getGroupSelectList();
  // storeFormRef.value.setFormData({
  //   group_id: 0
  // });

  getProvinceCity().then(res => {
    provinceCity.value = res.data;
    storeFormRef.value.setFormProps("province", {
      options: provinceCity.value
    });

    getCityList(storeFormData.value.province);
  });
  console.log(props.storeData);
  storeFormRef.value.setFormData(props.storeData);
};

const getCityList = (val: string) => {
  if (val) {
    const find = provinceCity.value.find(item => item.value === val);
    storeFormRef.value.setFormProps("city", {
      options: find?.children ?? []
    });
  }
};

const handleStoreFormList = () => {
  const list = cloneDeep(storeAcList);
  // list[list.length - 1] = storeGroupSelect("group_idlist", {}, true);
  if (props.isModal) {
    storeFormList.value = list.map(v => {
      if (v.key === "province") {
        v.onChange = (val: string) => {
          getCityList(val);
        };
      } else if (v.key === "phone") {
        v.rules = [
          {
            pattern: /^\+?[1-9]\d{1,14}$/,
            message: t("account_manage.form.phone_format"),
            trigger: "blur"
          }
        ];
      }
      return v;
    });
  } else {
    storeFormList.value = list.map(v => {
      v.span = 12;
      if (v.key === "city") {
        v.span = 12;
      }
      if (v.key === "detail_address") {
        v.span = 24;
      }
      if (v.key === "phone") {
        v.rules = [
          {
            pattern: /^\+?[1-9]\d{1,14}$/,
            message: t("account_manage.form.phone_format"),
            trigger: "blur"
          }
        ];
      }
      if (v.key === "province") {
        v.onChange = (val: string) => {
          getCityList(val);
        };
      }
      return v;
    });
  }
};
// endregion

// region 组件事件的集合
const handleStoreForm = (data: Record<string, any>) => {
  emit("handleConfirm", data);
};

const close = () => {
  // storeFormData.value = {
  //   name: "",
  //   province: "",
  //   city: "",
  //   detail_address: "",
  //   operator: "",
  //   phone: "",
  //   group_id: ""
  // };
  storeFormRef.value.reset();
  emit("update:showModal", false);
};

const addGroupForm = () => {
  showAddGroupModal.value = true;
};

const handleGroupForm = (data: GroupProp) => {
  if (!data.parent_id && data.parent_id !== 0) data.parent_id = 0;
  addStoreGroup(data).then(async res => {
    ElMessage({
      message: t("store_group.form.add_success"),
      type: "success"
    });
    await getGroupSelectList();
    storeFormRef.value.setFormData({
      group_id: res.data.id
    });
    showAddGroupModal.value = false;
  });
};
// endregion

// region 组件事件的集合
watch(
  () => [props.showModal, props.storeData],
  ([val, row]: [boolean, Record<string, any>]) => {
    showAddStorePopup.value = val;
    if (val) {
      nextTick(() => {
        getList();
      });
      title.value = row.id
        ? "device_manage.form.edit_store"
        : "device_manage.form.add_store";
      // storeFormData.value = row;
    } else {
      storeFormData.value = {
        name: "",
        province: "",
        city: "",
        detail_address: "",
        operator: "",
        phone: "",
        group_id: ""
      };
      storeFormRef.value?.reset();
    }
  }
);
// watch(
//   () => props.storeData,
//   val => {
//     storeFormData.value = val;
//   }
// );

onMounted(() => {
  handleStoreFormList();
});

defineExpose({
  getFormData: () => storeFormRef.value.getFormData(),
  getList,
  reset: () => storeFormRef.value.reset()
});
// endregion
</script>
